// Copyright 2013 Vedran Vuk. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package osutil provides helper functions related to os package(s).
package osutil

import (
	"errors"
	"os"
	"os/exec"
	"runtime"
	"syscall"
)

// Returns home dir of current user and a nil error on sucess or an empty string
// and an error on fail. 1ms response time as opposed to 4s of querying 
// os/user.Current().HomeDir.
func GetHomeDir() (string, error) {
	t, e := syscall.OpenCurrentProcessToken()
	if e != nil {
		return "", e
	}
	s, e := t.GetUserProfileDirectory()
	if e != nil {
		return "", e
	}
	return s, nil
}

// Returns true if "file" exists, error if not.
func FileExists(file string) bool {
	f, e := os.Open(file)
	if e != nil {
		return !os.IsNotExist(e)
	}
	f.Close()
	return true
}

// ShellExecute-like
func ExecuteFile(file string) error {
	var err error = nil
	switch runtime.GOOS {
	case "darwin":
		err = exec.Command("open", file).Start()
	case "linux":
		err = exec.Command("xdg-open", file).Start()
	case "windows":
		err = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", file).Start()
	default:
		err = errors.New("ExecuteFile: Unsupported platform.")
	}
	return err
}
